﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Batbaille.TAC;

namespace TestForeignVocabulary
{
    public partial class FormMain : Form
    {         
    #region Constants

        const int COL_SCORE = 0;
        const int COL_TRANS = 2;
        const int COL_VERIF = 3;
        const int COL_COREC = 1;

    #endregion
	#region Attributs & Properties

		private bool _bIsGUIInitializing;
		public bool IsGUIInitializing
		{
			get { return _bIsGUIInitializing; }
			set { _bIsGUIInitializing = value; }
		}

		private FicheInfo _oFiche;
		public FicheInfo Fiche
		{
			get { return _oFiche; }
			set { _oFiche = value; }
		}

    #endregion
    #region Constructors

        public FormMain()
        {			
			// Création de l'obj Fiche
			Fiche = new FicheInfo();

			// Initialisation système
            InitializeComponent();

			// Initialisation des composants GUI
			IsGUIInitializing = true;
			Initialize_TransDirection();
            Initialize_NbTranslation();
			Initialize_Difficulty();
            Initialize_NbAttemptInProgress();            
            Initialize_Score();
            Initialize_ListTrans();
			
			IsGUIInitializing = false;

			// Initialisation des boutons
            btNext.Enabled  = false;
            btVerif.Enabled = false;

            UpdateTitre("");
        }       

    #endregion
    #region Methods - GUI Components
    #region Methods - GUI Components : TransDirection

		void Initialize_TransDirection()
        {
            cbTrad.Items.Clear();
            cbTrad.Items.Add("FR -> EN");
            cbTrad.Items.Add("EN -> FR");

			Display_TransDirection();
        }

		void Display_TransDirection()
        {
            if( Fiche.ExerciceTrad.TheTransDirection == TransDirection.Normal)
            {
                cbTrad.Text = "FR -> EN";
            }
            else
            {                
                cbTrad.Text = "EN -> FR";
            }
        }

		void OnChange_TransDirection()
        {
            if( cbTrad.Text == "FR -> EN" )
				Fiche.ExerciceTrad.TheTransDirection = TransDirection.Normal;
            else
				Fiche.ExerciceTrad.TheTransDirection = TransDirection.Reverse;

			Display_TransDirection();
            InitExercice();
        }

	#endregion
	#region Methods - GUI Components : NbTranslation

		void Initialize_NbTranslation()
        {
			Display_NbTranslation();
        }

		void Display_NbTranslation()
        {
            tbNbMot.Text = Fiche.NbTranslation.ToString();
        }

		void OnChange_NbTranslation()
        {
			string strNum = tbNbMot.Text;

			try
			{
				Fiche.NbTranslation = int.Parse(strNum);

				InitExercice();
			}
			catch(Exception e)
			{		
				
				Batbaille.TAC.Message.Exception(e);			
			}

			Display_NbTranslation();
        }

	#endregion
		#region Methods - GUI Components : Difficulty

		void Initialize_Difficulty()
		{
			Display_Difficulty();
		}

		void Display_Difficulty()
		{
			tbDifficulty.Text = Fiche.ExerciceTrad.PercentDifficulty.ToString();
		}

		void OnChange_Difficulty()
		{
			try
			{			
				Fiche.ExerciceTrad.PercentDifficulty = int.Parse(tbDifficulty.Text);
			}
			catch( Exception )
			{
			}

			InitExercice();
		}

		#endregion
	#region Methods - GUI Components : Score

		void Initialize_Score()
        {
			Display_Score();
        }

        void Display_Score()
        {
            double dPercent = 0;
			if (Fiche.NbTranslation != 0)
				dPercent = Fiche.ExerciceTrad.NbTranslatedOfExercice * 100 / Fiche.NbTranslation;

			tbScore.Text = string.Format("{0}/{1} ({2}%)", Fiche.ExerciceTrad.NbTranslatedOfExercice.ToString(), Fiche.NbTranslation.ToString(), dPercent.ToString());
        }        

	#endregion
	#region Methods - GUI Components : NbAttemptInProgress

		public void Initialize_NbAttemptInProgress()
        {
			Display_NbAttemptInProgress();
        }

		public void Display_NbAttemptInProgress()
        {
			//tbTentative.Text = Fiche.NbAttemptInProgress.ToString() + " / " + Fiche.NbAttemptInProgress.ToString();
            tbTentative.Text = Fiche.NbAttemptInProgress.ToString();
        }       

    #endregion
	#region Methods - GUI Components : ListTrans

		void Initialize_ListTrans()
        {
            dgvExercice.Columns[COL_SCORE].HeaderText = "Difficulté";
            dgvExercice.Columns[COL_COREC].HeaderText = "Correction";

            // Gestion du nom de l'entête de colone
            if( Fiche.ExerciceTrad.TheTransDirection == TransDirection.Normal)
            {
                dgvExercice.Columns[COL_TRANS].HeaderText = "FR";
                dgvExercice.Columns[COL_VERIF].HeaderText = "EN";
            }
            else
            {
                dgvExercice.Columns[COL_TRANS].HeaderText = "EN";
                dgvExercice.Columns[COL_VERIF].HeaderText = "FR";
            }
            dgvExercice.Columns[COL_SCORE].ReadOnly = true;
            dgvExercice.Columns[COL_TRANS].ReadOnly = true;
            dgvExercice.Columns[COL_COREC].ReadOnly = true;

            dgvExercice.RowHeadersVisible = false;
        }

		void Display_ListTrans()
        {
            dgvExercice.Rows.Clear();

			if( Fiche.ExerciceTrad.NbNotTranslatedOfExercice <= 0 )
				return;

			dgvExercice.Rows.Add(Fiche.ExerciceTrad.NbNotTranslatedOfExercice);

			bool bFR2EN = Fiche.ExerciceTrad.TheTransDirection == TransDirection.Normal;
            int l=0;
			foreach (Translation oTrad in Fiche.ExerciceTrad.ListTransExercice)
            {
                if (oTrad.IsTranslatedAtLeastOnce && !Fiche.HasOptionLaisserAfficherMotTraduit) continue;

				if (oTrad.IsTranslatedAtLeastOnce && Fiche.HasOptionLaisserAfficherMotTraduit)
                {
                    dgvExercice.Rows[l].Cells[COL_VERIF].Value              = oTrad.WordToTrans;
                    dgvExercice.Rows[l].Cells[COL_VERIF].Style.BackColor    = Color.LightGreen;
                    dgvExercice.Rows[l].Cells[COL_VERIF].ReadOnly           = true;                    
                }

                dgvExercice.Rows[l].Cells[COL_SCORE].Style.BackColor = Color.Gainsboro;
                dgvExercice.Rows[l].Cells[COL_COREC].Style.BackColor = Color.Gainsboro;
                dgvExercice.Rows[l].Cells[COL_TRANS].Style.BackColor = Color.Gainsboro;

				dgvExercice.Rows[l].Cells[COL_TRANS].Value = oTrad.WordFromTrans;
                dgvExercice.Rows[l].Cells[COL_SCORE].Value = oTrad.PercentMistake+" %";
                l++;
            }
        }

        #endregion
    #endregion
	#region Methods - Other

		void DisplayAll()
        {
			Display_TransDirection();
            Display_NbTranslation();
			Display_Difficulty();
            Display_NbAttemptInProgress();
            Display_ListTrans();            
            Display_Score();
        }

    #endregion
	#region Methods - Operation

		void InitExercice()
        {
            Fiche.InitExercise();
            
            DisplayAll();            

            btNext.Enabled = false;
            btVerif.Enabled = true;
        }

        void NextExercice()
        {               
            Fiche.NextExercise();

            DisplayAll();

            btNext.Enabled = false;
            btVerif.Enabled = true;
        }

        void VerifExercice()
        {
            if(Fiche.ExerciceTrad.NbTranslationExercice <= 0) return;

			int nNbTranslatedOfAttempt  = 0;
			int nNbTranslationOfAttempt = Fiche.ExerciceTrad.NbNotTranslatedOfExercice;
			
            for (int l = 0; l < dgvExercice.Rows.Count; l++)
            {               
                object oWordToTranslate = dgvExercice.Rows[l].Cells[COL_TRANS].Value;
                object oWordToVerif     = dgvExercice.Rows[l].Cells[COL_VERIF].Value;
                //object oScore           = dgvExercice.Rows[l].Cells[COL_SCORE].Value;
                
                //if( oScore != null && oScore.GetType() == typeof(int) )
                {
                    Color oColor = Color.LightCoral;
                    if( oWordToTranslate != null    && oWordToTranslate.GetType()   == typeof(string) )
                    {
                        string strWordToTranslate   = oWordToTranslate.ToString();

						string strProposition = "";
                        if( oWordToVerif != null        && oWordToVerif.GetType()       == typeof(string) )
                        {
							strProposition = oWordToVerif.ToString();
                        }

						if (Fiche.ExerciceTrad.Verification(strWordToTranslate, strProposition))
						{
							oColor = Color.LightGreen;
							nNbTranslatedOfAttempt++;
						}

						Translation oTrans = Fiche.ExerciceTrad.FindFromTranslateInExercise( strWordToTranslate );

						dgvExercice.Rows[l].Cells[COL_COREC].Value = oTrans.WordToTrans;
						dgvExercice.Rows[l].Cells[COL_SCORE].Value = oTrans.PercentMistake + " %";
                    }

                    dgvExercice.Rows[l].Cells[COL_COREC].Style.BackColor = oColor;
                    dgvExercice.Rows[l].Cells[COL_TRANS].Style.BackColor = oColor;
                    dgvExercice.Rows[l].Cells[COL_VERIF].Style.BackColor = Color.Gainsboro;
                    dgvExercice.Rows[l].Cells[COL_VERIF].ReadOnly        = true;
                }
            }

            double dPercentReussite = 0;			
			if (nNbTranslationOfAttempt != 0)
				dPercentReussite = nNbTranslatedOfAttempt * 100 / nNbTranslationOfAttempt;

			MessageBox.Show(String.Format("{0} mot(s) trouvés sur {1} ({2}%)", nNbTranslatedOfAttempt.ToString(), nNbTranslationOfAttempt.ToString(), dPercentReussite.ToString()));
            Display_NbAttemptInProgress();
            Display_Score();
                        
            btNext.Enabled = true;
            btVerif.Enabled = false;
        }

        private void OnImport()
        {
            var OpenFileDialog	  = new OpenFileDialog();
			OpenFileDialog.Filter = "xls files (*.xls)|*.xls|xlsx files (*.xlsx)|*.xlsx|Tous les fichiers (*.*)|*.*";
           
		    OpenFileDialog.InitialDirectory = Fiche.OptionEnglishDirectoryPath;
			OpenFileDialog.FilterIndex = Fiche.OptionEnglishFilterIndexExtension;
            if (OpenFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string strFileName = OpenFileDialog.FileName;
				Fiche.OptionEnglishDirectoryPath = strFileName;
				Fiche.OptionEnglishFilterIndexExtension = OpenFileDialog.FilterIndex;

                Fiche.Import(strFileName);
                Display_NbTranslation();
                InitExercice();
                MessageBox.Show(String.Format("Import de {0} mot(s)",Fiche.ExerciceTrad.ListTransImport.Count));
				UpdateTitre(String.Format("(Import : {0})", OpenFileDialog.SafeFileName));
            }       
        }

		private void OnExport()
		{
			var oSaveFileDialog = new SaveFileDialog();
			oSaveFileDialog.Filter = "xls files (*.xls)|*.xls|xlsx files (*.xlsx)|*.xlsx|Tous les fichiers (*.*)|*.*";

			oSaveFileDialog.InitialDirectory = Fiche.OptionEnglishDirectoryPath;
			oSaveFileDialog.FilterIndex = Fiche.OptionEnglishFilterIndexExtension;
			if (oSaveFileDialog.ShowDialog(this) == DialogResult.OK)
			{
				string strFileName = oSaveFileDialog.FileName;

				if (!System.IO.File.Exists(strFileName))
				{
					System.IO.File.Create(strFileName);					
					//FileStream stream = new FileStream("demo.xls", FileMode.OpenOrCreate);
					//stream.Close();
				}

				
				Fiche.OptionEnglishDirectoryPath = strFileName;
				Fiche.OptionEnglishFilterIndexExtension = oSaveFileDialog.FilterIndex;

				Fiche.Export(strFileName);
				Display_NbTranslation();
				InitExercice();
				MessageBox.Show(String.Format("Export de {0} mot(s)", Fiche.ExerciceTrad.ListTransDico.Count));				
			}
		}

		void UpdateTitre(string strPostTitre)
        {
			this.Text = FicheInfo.APPLICATION_NAME + " - " + FicheInfo.APPLICATION_VERSION;
                //System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
            if( strPostTitre.Length > 0 )
                this.Text += (" "+strPostTitre);
        }

		bool IsExit()
		{
			if(MessageBox.Show("Etes-vous certain de vouloir quitter ?", "Quitter", MessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				Fiche.SaveDico();
				return true;
			}
			return false;
		}

    #endregion
    #region Event
	
		private void FormMain_FormClosing(Object sender, FormClosingEventArgs e)
		{		
			if( !IsExit() )	
				e.Cancel = true;
		}

		private void FormMain_Load(object sender, EventArgs e)
		{

		}

        // Click bouton FERMER
        private void btFermer_Click(object sender, EventArgs e)
        {			
			Application.Exit();
        }

        // Change combobox TRAD
        private void cbTrad_SelectedIndexChanged(object sender, EventArgs e)
        {
            if( !IsGUIInitializing )
                OnChange_TransDirection();
        }

        // Change NBMOT
        private void tbNbMot_TextChanged(object sender, EventArgs e)
        {
			if (!IsGUIInitializing)
                OnChange_NbTranslation();
        }        

        // Click bouton INITIALISER
        private void btInit_Click(object sender, EventArgs e)
        {
            InitExercice();
        }

        // Click bouton SUIVANT
        private void btNext_Click(object sender, EventArgs e)
        {
            NextExercice();
        }

        // Click bouton VERIFIER
        private void btVerif_Click(object sender, EventArgs e)
        {   
            VerifExercice();
        }
        
        // Click menu IMPORT
        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OnImport();
        }
        
        // Click menu ENREGISTRER DICO
        private void enregisterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Fiche.SaveDico();
            MessageBox.Show(String.Format("Sauvegarde de {0} mot(s)",Fiche.ExerciceTrad.ListTransDico.Count));
        }

            

		// Click Fermer
        private void fermerToolStripMenuItem_Click(object sender, EventArgs e)
        {					
			Application.Exit();
        }

		// Ouverture Menu option
		private void optionToolStripMenuItem1_Click(object sender, EventArgs e)
		{
			FormOption frm = new FormOption(Fiche);
			frm.Show();
		}

        #endregion

		private void tbDifficulty_TextChanged(object sender, EventArgs e)
		{
			if (!IsGUIInitializing)
				OnChange_Difficulty();
		}		

		private void chargerDicoToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Fiche.ExerciceTrad.ListTransImport.Clear();
			Fiche.NbTranslation = -1;
			InitExercice();
			UpdateTitre(String.Format("(Dico)"));
		}
				
		// Click menu VIDER DICO
        private void viderDicoToolStripMenuItem_Click(object sender, EventArgs e)
        {
			if(MessageBox.Show("Etes-vous certain de vouloir vider le dictionnaire ?", "Vider Dico", MessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				int nNbMotSave = Fiche.ExerciceTrad.ListTransDico.Count;

				Fiche.ClearDico();
				MessageBox.Show(String.Format("Supression de {0} mot(s)",nNbMotSave));			
				InitExercice();
			}
        }    
		
    }

    
    
}
